package com.my.algorithmlearning.leetcode;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName Medium_78_PowerSet
 * @Description Medium_78_PowerSet
 * @Author wanghaiwei
 * @Date 2023/3/22 10:33
 */
public class Medium_78_PowerSet {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> results = new ArrayList<>();
        results.add(new ArrayList<>());
        if (nums == null || nums.length == 0) {
            return results;
        }
        if (nums.length == 1) {
            results.add(Collections.singletonList(nums[0]));
            return results;
        }
        backtrack(nums, 0, results, new ArrayList<>());
        return results;
    }

    private void backtrack(int[] nums, int currIdx, List<List<Integer>> results, List<Integer> tmp) {
        if (currIdx == nums.length) {
            return;
        }
        for (int i = currIdx; i < nums.length; i++) {
            tmp.add(nums[i]);
            results.add(new ArrayList<>(tmp));
            backtrack(nums, i + 1, results, tmp);
            tmp.remove(tmp.size() - 1);
        }
    }

    public static void main(String[] args) {
        Medium_78_PowerSet solution = new Medium_78_PowerSet();
        List<List<Integer>> result = solution.subsets(new int[]{1, 2, 3});
        System.out.printf("Input: nums = [1,2,3]，输出结果：%s \n", result.stream().map(r -> "[" + StringUtils.join(r, ',') + "]").collect(Collectors.joining(",")));
        result = solution.subsets(new int[]{0});
        System.out.printf("Input: nums = [0]，输出结果：%s \n", result.stream().map(r -> "[" + StringUtils.join(r, ',') + "]").collect(Collectors.joining(",")));
    }
}
